﻿//using LitJson;
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using JSON;
public enum GameNetState{
	CloseSendLoad,
}
public class NetSendObj{
	public byte[] msg;
	public NetCommand command;
	public Action<JSONNode> func;
	public NetSendObj(byte[] _msg, NetCommand _commandId, Action<JSONNode> _func){
		msg = _msg;
		command = _commandId;
		func = _func;
	}
}
public class SocketManager
{
	private Dictionary<NetCommand, Action<JSONNode>> _FuncList;
    public NetMgr _NetMgr;
    private NetSendObj bak;
    public static bool m_bIsConnect = false;
    const string SocketKey = "yinghuang";
	public Action<NetCommand,JSONNode> ReceiveData;

    public SocketManager()
    {
		_FuncList = new Dictionary<NetCommand, Action<JSONNode>>();
    }

    public void Connect()
    {
        _NetMgr = new NetMgr();
        _NetMgr.Connect();
    }

    public static SocketManager Instance;
    public static SocketManager GetInstance()
    {
        if (Instance == null)
        {
            Instance = new SocketManager();
        }
        return Instance;
    }

    public static void Destroy()
    {
        Instance = null;
    }

    public void RecvMessage(NetCommand commandId, JSONNode jData)
    {
		Debug.Log((GameSetting.Instance.NET_OPEN == true?"":"本地测试模式!!!!")+"NETRECV: id :" + commandId + " data :" + jData.ToString());
        Loom.QueueOnMainThread(() =>
        {
//            Debug.Log("RecvMessage id :" + commandId + " data :" + jData.ToJson());
//            GameManager.GetInstance().CloseSendLoading();
//            bak = null;
        });
//
        bool isFunc = _FuncList.ContainsKey(commandId);
		if (jData["State"].AsInt == 1)
        {
            if (isFunc)
            {
                Loom.QueueOnMainThread(() =>
                {
                    if (_FuncList.ContainsKey(commandId))
                    {
                        if (jData["Data"].ToString().Length > 1)
							if(ReceiveData!=null)
								ReceiveData(commandId,jData["Data"]);
						BaseModel.Instance.ReceiveData(commandId, jData["Data"]);
                        _FuncList[commandId](jData);
                        _FuncList.Remove(commandId);
                    }
                    else
                    {
                        Debug.LogError("Not Contains Key :" + commandId);
                    }

                });
            }
            else
            {
                PushMessage(commandId, jData);
            }
        }
        else
        {
			if (isFunc) {
				Loom.QueueOnMainThread (() => {
//                GameManager.GetInstance().AddGameState(GameState.EGameStateDiaglg, jData);
					if(_FuncList.ContainsKey(commandId)){
						Debug.Log ("ErrorData ... " + jData ["Data"]);
						BaseModel.Instance.ReceiveErrorData(commandId, jData);
						if (isFunc) {
							_FuncList.Remove (commandId);
						}
					}
				});
			}
        }
    }


    //private 

	public void SendMessage(ListJsonData jData, NetCommand commandId, Action<JSONNode> func)
    {
		Debug.Log((GameSetting.Instance.NET_OPEN == true?"":"本地测试模式!!!!")+ "NETSEND: id :" + commandId + " data :" + jData.GetString());
	
//		return;
        //string encrtptStr = XXTea.Encrypt(jData.ToJson(), SocketKey);
        //byte[] msg = System.Text.UTF8Encoding.UTF8.GetBytes(encrtptStr);

//        byte[] msg = XXTea.Encrypt2(jData.ToJson(), SocketKey);
		byte[] msg = XXTea.Encrypt2(jData.GetString(), SocketKey);
        SendMessage(msg, commandId, func);
    }

	void SendMessage(byte[] msg, NetCommand commandId, Action<JSONNode> func)
    {
        if (!m_bIsConnect)
            return;

        if (bak == null && commandId != NetCommand.ELoginUser)
        {
//            GameManager.GetInstance().ShowSendLoading();
            bak = new NetSendObj(msg, commandId, func);
        }

        //string str = System.Text.Encoding.Default.GetString(msg);
        //Debug.Log("SendMessage id :" + commandId + " data :" + str);

        bool isFunc = _FuncList.ContainsKey(commandId);
//        Debug.Log("Is Func: " + isFunc);
		if (!isFunc && func!=null)
            _FuncList.Add(commandId, func);
		else
			Debug.LogError ("!!!");
		if (!GameSetting.Instance.NET_OPEN)
			return;
        _NetMgr.SendMsg(msg, commandId);
    }



	void PushMessage(NetCommand commandId, JSONNode jData)
    {
        Loom.QueueOnMainThread(() =>
        {
//				if(ReceiveData!=null)
//					ReceiveData(commandId,jData["Data"]);
//				BaseModel.Instance.ReceiveData(commandId, jData["Data"]);
//
        });
        Debug.Log(jData["Data"]);
    }

    public void ReSend()
    {
        if (bak != null && _FuncList.ContainsKey(bak.command))
        {
            //Debug.LogError("RE SendMessage id :" + bak.command + " data :" + System.Text.Encoding.Default.GetString(bak.msg));
            _NetMgr.SendMsg(bak.msg, bak.command);
        }
    }

    public void Reconnect()
    {
        if (_NetMgr.Reconnect())
        {
//            JsonData jData = new JsonData();
//            jData["UUID"] = LsTools.GetUUID();
//            jData["Simple"] = 1;
//            jData["Repeat"] = 1;
			ListJsonData list =  ListJsonData.Init();
			list.Add ("UUID", BaseModel.Instance.UUID);
			list.Add ("Simple", 1);
			list.Add ("Repeat", 1);
			SendMessage(list, NetCommand.ELoginUser, delegate(JSONNode data) { ReSend(); });
        }
    }
}
